package com.gabejeff.engine;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import javax.imageio.ImageIO;

import com.gabejeff.exceptions.TileNotFoundException;

public class TileFactory {
	
	private static TileFactory instance;
	
	private static HashMap<Integer, BufferedImage> tileMap;
	
	static{
		instance = new TileFactory();
	}
	/**
	 * Private constructor.  Creates a hashmap of tile values to point locations
	 */
	private TileFactory() {
		tileMap = new HashMap<Integer, BufferedImage>();
		// Things to do:
		// Populate the tile hashmap with all of the possible tile images. 
		// There should be a relatively low number of tiles required.
		URL spriteURL = this.getClass().getResource("/com/gabejeff/res/Tileset.png");
		try {
			BufferedImage sprites = ImageIO.read(spriteURL);
			int numRows = sprites.getHeight() / 32;
			int numCols = sprites.getWidth() / 32;
			for (int row=0;row<numRows;row++) {
				for (int col=0;col<numCols;col++) {
					tileMap.put(tileMap.size()+1, sprites.getSubimage(col*32, row*32, 32, 32));
				}
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * @return An instance of the tile factory
	 */
	public static TileFactory getInstance() {
		/*
		if (!instantiated) {
			instance = new TileFactory();
			instantiated = true;
		} // */
		return instance;
	}
	
	/**
	 * Retrieves an image of the tile specified by the tile number, n.
	 * @param n The tile number
	 * @return A BufferedImage of the tile
	 */
	public BufferedImage produceTile(int n) throws TileNotFoundException {
		if (!tileMap.containsKey(n)) {
			// Things to do:
			// Check if the image has the tile and if it does then load it into the hashmap
			throw new TileNotFoundException();
		}
		return tileMap.get(n);
	}

}
